import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/reg_new_qr.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/core/providers/app_model.dart';
import 'package:mall/core/providers/pages/mine/login_model.dart';
import 'package:mall/core/providers/pages/mine/store_logo_query_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/screens/main/main_page.dart';
import 'package:mall/screens/mine/forget_page.dart';
import 'package:mall/screens/mine/register_page.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../theme.dart';

/// 登录页面
class LoginPage extends StatefulWidget {
  static const routeName = '/LoginPage';
  final String args;

  const LoginPage({
    Key key,
    this.args,
  }) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  GlobalKey<AutoCompleteTextFieldState<String>> _key = GlobalKey();
  TextEditingController _usernameController;
  TextEditingController _passwordController;

  static const String _USERNAME_SUGGESTIONS = 'username_suggestions';
  List<String> _suggestions = [];

  @override
  void initState() {
    super.initState();
    _usernameController = TextEditingController(text: widget.args);
    _passwordController = TextEditingController();

    _getUsernameSuggestions().then((value) {
      debugPrint('$value');
      _key.currentState.updateSuggestions(value);
    }).catchError((error) {
      debugPrint('$error');
    });
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => StoreLogoQueryModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => LoginModel(context.read<Auth>()))
      ],
      child: Theme(
        data: darkTheme(),
        child: Scaffold(
          body: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 100),
                  child: Consumer<StoreLogoQueryModel>(
                    builder: (context, model, child) {
                      switch (model.viewState) {
                        case ViewState.success:
                          return ImageNetwork(
                            url: '${model.data}',
                            width: 110,
                            height: 55,
                            fit: BoxFit.contain,
                          );
                        default:
                          return SizedBox(width: 110, height: 55);
                      }
                    },
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 16),
                  child: Text(
                    '帮你开启财富自由之路',
                    style: TextStyle(fontSize: 18),
                  ),
                ),
                Text(
                  'Help you open the way to wealth freedom',
                  style: TextStyle(fontSize: 12),
                ),
                _WrapContainer(
                  margin: EdgeInsets.only(top: 55),
                  child: SimpleAutoCompleteTextField(
                    controller: _usernameController,
                    decoration: InputDecoration(
                      icon: ImageIcon(AssetImage('assets/images/login/ic_username.png')),
                      hintText: '账户',
                    ),
                    key: _key,
                    suggestions: _suggestions,
                  ),
                ),
                _WrapContainer(
                  margin: EdgeInsets.only(top: 15),
                  child: TextFormField(
                    controller: _passwordController,
                    decoration: InputDecoration(
                      icon: ImageIcon(AssetImage('assets/images/login/ic_password.png')),
                      hintText: '密码',
                    ),
                    obscureText: true,
                  ),
                ),
                SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    FlatButton(
                      onPressed: _register,
                      child: Text('快速注册>'),
                    ),
                    FlatButton(
                      onPressed: () {
                        Navigator.of(context).pushNamed(ForgetPage.routeName);
                      },
                      child: Text('忘记密码>'),
                    ),
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 16),
                  width: double.infinity,
                  child: Consumer<LoginModel>(
                    builder: (context, model, child) {
                      switch (model.viewState) {
                        case ViewState.busy:
                          return OutlineButton(
                            onPressed: null,
                            borderSide: BorderSide(
                              color: Colors.white,
                            ),
                            child: CircularProgressIndicator(),
                          );
                        default:
                          return OutlineButton(
                            onPressed: () => _login(context, model),
                            borderSide: BorderSide(
                              color: Colors.white,
                            ),
                            child: Text(
                              '登录',
                              style: TextStyle(color: Colors.white, fontSize: 18),
                            ),
                          );
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 读取用户名
  Future<List<String>> _getUsernameSuggestions() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.getStringList(_USERNAME_SUGGESTIONS);
  }

  /// 记住用户名
  Future<bool> _setUsername(String username) async {
    if (_suggestions.contains(username)) {
      return false;
    }
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    final list = _suggestions..insert(0, username);
    return await sharedPreferences.setStringList(_USERNAME_SUGGESTIONS, list);
  }

  /// 注册
  void _register() async {
    // 注册成功，返回账号密码，自动填入
    final result = await Navigator.of(context).pushNamed(RegisterPage.routeName);
    if (result == null || result is! RegNewQr) {
      return;
    }
    // 自动填入
    final regNewQr = result as RegNewQr;
    _usernameController.text = "${regNewQr.username}";
  }

  /// 登录
  void _login(BuildContext context, LoginModel model) async {
    var username = _usernameController.text;
    var password = _passwordController.text;
    // 保存账号
    await _setUsername(username);
    // 登录
    LoginModel loginModel = Provider.of(context, listen: false);
    ViewState viewState = await loginModel.oauthToken(username, password);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(model.errorMessage);
        break;
      default:
        AppModel appModel = Provider.of(context, listen: false);
        // 更新token
        appModel.accessToken = loginModel.accessToken.accessToken;
        // 重置当前店铺
        appModel.currentStoreId = null;
        // 转到新页面栈
        Navigator.of(context).pushNamedAndRemoveUntil(MainPage.routeName, (route) => false);
        break;
    }
  }
}

class _WrapContainer extends StatelessWidget {
  final EdgeInsetsGeometry margin;
  final Widget child;

  _WrapContainer({
    Key key,
    this.margin,
    this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(
        horizontal: 16,
      ),
      color: Colors.white10,
      height: 50,
      margin: margin,
      child: child,
    );
  }
}
